const mongoose = require('mongoose');

const roomSchema = new mongoose.Schema({
  roomCode: {
    type: String,
    required: true,
    unique: true
  },
  name: {
    type: String,
    required: true,
    trim: true,
    maxlength: 50
  },
  creator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  members: [{
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    },
    username: String,
    nickname: String,
    isOnline: {
      type: Boolean,
      default: true
    },
    joinedAt: {
      type: Date,
      default: Date.now
    },
    currentBalance: {
      type: Number,
      default: 0
    }
  }],
  maxMembers: {
    type: Number,
    default: 8,
    min: 2,
    max: 20
  },
  isActive: {
    type: Boolean,
    default: true
  },
  // 房间状态：1-开启，2-关闭
  status: {
    type: Number,
    enum: [1, 2],
    default: 2
  },
  isPrivate: {
    type: Boolean,
    default: false
  },
  password: {
    type: String,
    default: null
  },
  gameHistory: [{
    timestamp: {
      type: Date,
      default: Date.now
    },
    transactions: [{
      from: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      to: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      amount: Number,
      description: String
    }],
    totalAmount: Number
  }],
  settings: {
    minBet: {
      type: Number,
      default: 1
    },
    maxBet: {
      type: Number,
      default: 100
    },
    autoStart: {
      type: Boolean,
      default: false
    }
  }
}, {
  timestamps: true
});

// 生成房间号
roomSchema.statics.generateRoomCode = function() {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

// 检查房间号是否可用
roomSchema.statics.isRoomCodeAvailable = async function(roomCode) {
  const existingRoom = await this.findOne({ roomCode });
  return !existingRoom;
};

// 添加成员
roomSchema.methods.addMember = function(userId, username, nickname) {
  const existingMember = this.members.find(member => 
    member.user.toString() === userId.toString()
  );
  
  if (!existingMember && this.members.length < this.maxMembers) {
    this.members.push({
      user: userId,
      username,
      nickname: nickname || username,
      isOnline: true,
      currentBalance: 0
    });
    return true;
  }
  return false;
};

// 移除成员
roomSchema.methods.removeMember = function(userId) {
  const memberIndex = this.members.findIndex(member => 
    member.user.toString() === userId.toString()
  );
  
  if (memberIndex !== -1) {
    this.members.splice(memberIndex, 1);
    return true;
  }
  return false;
};

// 更新成员在线状态
roomSchema.methods.updateMemberStatus = function(userId, isOnline) {
  const member = this.members.find(member => 
    member.user.toString() === userId.toString()
  );
  
  if (member) {
    member.isOnline = isOnline;
    return true;
  }
  return false;
};

// 添加游戏记录
roomSchema.methods.addGameRecord = function(transactions, totalAmount) {
  this.gameHistory.push({
    transactions,
    totalAmount
  });
  
  // 更新成员余额
  transactions.forEach(transaction => {
    const fromMember = this.members.find(member => 
      member.user.toString() === transaction.from.toString()
    );
    const toMember = this.members.find(member => 
      member.user.toString() === transaction.to.toString()
    );
    
    // 确保amount按照人民币规则保留两位小数
    const amount = Math.round(Number(transaction.amount) * 100) / 100;
    
    if (fromMember) {
      fromMember.currentBalance -= amount;
    }
    if (toMember) {
      toMember.currentBalance += amount;
    }
  });
};

module.exports = mongoose.model('Room', roomSchema); 